/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.util.DocConverterUtils;
import com.koron.scene.domain.ProjectFile;
import com.koron.scene.mapper.ProjectFileMapper;
import com.koron.scene.service.api.ProjectFileService;
import com.koron.scene.utils.BaseEntityUtil;
import com.koron.scene.utils.BusinessCode;

import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;


import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProjectFileServiceImpl implements ProjectFileService {

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private DocConverterUtils docConverterUtils;

    private static final Logger logger = LoggerFactory.getLogger(ProjectFileServiceImpl.class);

    MessageBean<ProjectFile> addCheckAndBuild(String projectId, String enterpriseId, String sourceType, String fileName) {
        MessageBean<ProjectFile> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), ProjectFile.class);
        ProjectFile projectFile = new ProjectFile();
        if (StringUtils.isBlank(projectId) || StringUtils.isBlank(enterpriseId)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(fileName)) {
            msg.setCode(BusinessCode.PROJECT_FILE_NAME_CANNOT_EMPTY.getCode());
            msg.setDescription(BusinessCode.PROJECT_FILE_NAME_CANNOT_EMPTY.getDescription());
            return msg;
        }
        if (StringUtils.isBlank(sourceType)) {
            msg.setCode(BusinessCode.PROJECT_FILE_TYPE_CANNOT_EMPTY.getCode());
            msg.setDescription(BusinessCode.PROJECT_FILE_TYPE_CANNOT_EMPTY.getDescription());
            return msg;
        }
        projectFile.setProjectId(projectId);
        projectFile.setEnterpriseId(enterpriseId);
        projectFile.setFileName(fileName);
        projectFile.setSourceType(sourceType);
        msg.setData(projectFile);
        return msg;
    }

    @Override
    public MessageBean<?> addOrUpdate(StaffBean user, MultipartFile[] files, String projectFileId,
                                      String projectId, String enterpriseId, String sourceType, String fileName,
                                      String keepPathListStr, String deletePathListStr,
                                      String keepPrePathListStr, String deletePrePathListStr) {
        MessageBean<List> msg = new MessageBean<List>();
        SessionFactory factory = new SessionFactory();
        List<String> filePaths = new ArrayList<>();
        List<String> filePrePaths = new ArrayList<>();
        try {
            ProjectFileMapper fileMapper = factory.getMapper(ProjectFileMapper.class);
            MessageBean<ProjectFile> messageBean = addCheckAndBuild(projectId, enterpriseId, sourceType, fileName);
            if (messageBean.getCode() != 0) {
                factory.close(false);
                return messageBean;
            }
            ProjectFile projectFile = messageBean.getData();
            //保存附件
            String[] keepAddressArray = StringUtils.isEmpty(keepPathListStr) ? null : keepPathListStr.split("[,，]");
            String[] keepPreAddressArray = StringUtils.isEmpty(keepPrePathListStr) ? null : keepPrePathListStr.split("[,，]");
            List<String> keepAddressList = new ArrayList<>();
            List<String> keepPreAddressList = new ArrayList<>();
            if (keepAddressArray != null && keepAddressArray.length > 0) {
                keepAddressList = Arrays.asList(keepAddressArray).stream().collect(Collectors.toList());
            }
            if (keepPreAddressArray != null && keepPreAddressArray.length > 0) {
                keepPreAddressList = Arrays.asList(keepPreAddressArray).stream().collect(Collectors.toList());
            }
            if (files != null && files.length > 0) {
                for (MultipartFile file : files) {
                    if (file != null) {
                        String url = clientWrapper.uploadFile(file);
                        String filPath = url + "#" + file.getOriginalFilename();
                        keepAddressList.add(filPath);
                        filePaths.add(filPath);
//                        File pdfFile = DocConverterUtils.converter(file);
                        String pdfPath=docConverterUtils.converterUpdate(file);
                        if (pdfPath != null) {
//                            String pdfFilePath = clientWrapper.uploadFile(new FileInputStream(pdfFile), pdfFile.length(), FilenameUtils.getExtension(pdfFile.getName()));
                            keepPreAddressList.add(pdfPath);
                            filePrePaths.add(pdfPath);
                        } else {
                            keepPreAddressList.add(filPath);
                            filePrePaths.add(filPath);
                        }
                    }
                }
            }
            projectFile.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
            projectFile.setPreviewAttachment((keepPreAddressList == null || keepPreAddressList.size() <= 0) ? null : new Gson().toJson(keepPreAddressList));
            if (StringUtils.isEmpty(projectFileId)) {
                //新增
                BaseEntityUtil.setAddBaseProperties(projectFile, user);
                fileMapper.insert(projectFile);
            } else {
                BaseEntityUtil.setUpdateBaseProperties(projectFile, user);
                projectFile.setId(projectFileId);
                fileMapper.updateByPrimaryKeySelective(projectFile);
            }
            factory.close();
            msg.setCode(0);
            msg.setDescription("保存成功");
            if (StringUtils.isNotEmpty(deletePathListStr)) {
                String[] delArray = deletePathListStr.split("[,，]");
                for (String delAdr : delArray) {
                    clientWrapper.deleteFile(delAdr.split("#")[0]);
                }
            }
            if (StringUtils.isNotEmpty(deletePrePathListStr)) {
                String[] delArray = deletePrePathListStr.split("[,，]");
                for (String delAdr : delArray) {
                    clientWrapper.deleteFile(delAdr.split("#")[0]);
                }
            }
        } catch (Exception e) {
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            if (filePaths != null && !filePaths.isEmpty()) {
                for (String p : filePaths) {
                    clientWrapper.deleteFile(p.split("#")[0]);
                }
            }
            if (filePrePaths != null && !filePrePaths.isEmpty()) {
                for (String p : filePrePaths) {
                    clientWrapper.deleteFile(p.split("#")[0]);
                }
            }
            return msg;
        }finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> delete(StaffBean user, String projectFileId) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isBlank(projectFileId)) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            ProjectFileMapper mapper = factory.getMapper(ProjectFileMapper.class);
            ProjectFile projectFile = mapper.selectByPrimaryKey(projectFileId);
            if (projectFile != null) {
                if (StringUtils.isNotBlank(projectFile.getAttachment())) {
                    List<String> pathList = JSONObject.parseArray(projectFile.getAttachment(), String.class);
                    if (pathList != null && !pathList.isEmpty()) {
                        for (String p : pathList) {
                            clientWrapper.deleteFile(p.split("#")[0]);
                        }
                    }
                }
                if (StringUtils.isNotBlank(projectFile.getPreviewAttachment())) {
                    List<String> pathList = JSONObject.parseArray(projectFile.getPreviewAttachment(), String.class);
                    if (pathList != null && !pathList.isEmpty()) {
                        for (String p : pathList) {
                            clientWrapper.deleteFile(p.split("#")[0]);
                        }
                    }
                }
            }
            mapper.deleteByPrimaryKey(projectFileId);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> list(StaffBean user, String fileName, String sourceType, String projectId, String enterpriseId, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            ProjectFileMapper mapper = factory.getMapper(ProjectFileMapper.class);
            Integer start = null;
            if (page != null && pageSize != null && page > 0 && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            List<ProjectFile> projectTrainingList = mapper.list(fileName, sourceType, projectId, enterpriseId, start, pageSize);
            int total = mapper.listTotal(fileName, sourceType, projectId, enterpriseId);
            DataBean dataBean = new DataBean();
            dataBean.setList(projectTrainingList);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage(start == null ? null : total % pageSize == 0 ? total / pageSize : (total / pageSize + 1));
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }
}
